package com.example.itcacp.repository.mybatis;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.itcacp.entity.Comment;
import com.example.itcacp.entity.Like;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 评论Mapper层
 * */

@Repository
public interface CommentMapper extends BaseMapper<Comment> {


    /**
     * 查询顶级评论
     */
    @Select("SELECT pc.*, iu.username, iu.profile_photo_path " +
            "FROM pc_comment pc " +
            "LEFT JOIN it_user iu ON iu.user_id = pc.user_id " +
            "WHERE pc.target_id = #{contentId} AND pc.target_type = #{contentType} AND pc.parent_id IS NULL " +
            "ORDER BY created_at DESC")
    @Results({
            @Result(property = "commentId", column = "comment_id"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "user.profile_photo_path", column = "profile_photo_path"),
            @Result(property = "user.username", column = "username"),
            @Result(property = "children", column = "comment_id",
                    many = @Many(select = "com.example.itcacp.repository.mybatis.CommentMapper.findChildComments"))
    })
    List<Comment> findTopLevelComments(Long contentId, Like.ContentType contentType);

    /**
     * 查询子评论（与上述方法相同）
     */
    @Select("SELECT pc.*, iu.username, iu.profile_photo_path " +
            "FROM pc_comment pc " +
            "LEFT JOIN it_user iu ON iu.user_id = pc.user_id " +
            "WHERE pc.parent_id = #{commentId} " +
            "ORDER BY created_at DESC")
    @Results({
            @Result(property = "commentId", column = "comment_id"),
            @Result(property = "created_at", column = "created_at"),
            @Result(property = "user.profile_photo_path", column = "profile_photo_path"),
            @Result(property = "user.username", column = "username"),
            @Result(property = "children", column = "comment_id",
                    many = @Many(select = "com.example.itcacp.repository.mybatis.CommentMapper.findChildComments"))  // @Many 注解实现嵌套映射
    })
    List<Comment> findChildComments(Long commentId);

}
